import { _get, _post, loadimg, _post1 } from "../../../utils/request";
import util, { formatDate } from "../../../utils/util";
import { debounce, throttle } from "../../../utils/debounce";
const app = getApp();
Page({
    data: {
        templateIdArray: [],
        pickerArray: [],
        pickerIndex: 0,
        templateId: 0,
        form: [],
        testing: [],
        // test1_list: [{
        test1: "",
        test2_list: [
            // {
            //     test2: "紧急报警线路",
            //     result: [
            //         { name: "yes", value: "符合" },
            //         { name: "no", value: "不符合" },
            //     ],
            //     standard: "3-5",
            //     single: [
            //         { name: "yes", value: "符合" },
            //         { name: "no", value: "不符合" },
            //     ],
            // },
            // {
            //     test2: "报警联网",
            //     result: [
            //         { name: "yes", value: "符合" },
            //         { name: "no", value: "不符合" },
            //     ],
            //     standard: "3-5",
            //     single: [
            //         { name: "yes", value: "符合" },
            //         { name: "no", value: "不符合" },
            //     ],
            // },
        ],
        // },
        // {
        //     test1: "视频安防监控设施/系统",
        //     test2_list: [{
        //             test2: "紧急报警线路",
        //             result: [
        //                 { name: "yes", value: "符合" },
        //                 { name: "no", value: "不符合" },
        //             ],
        //             standard: "3-5",
        //             single: [
        //                 { name: "yes", value: "符合" },
        //                 { name: "no", value: "不符合" },
        //             ],
        //         },
        //         {
        //             test2: "紧急报警线路",
        //             result: [
        //                 { name: "yes", value: "符合" },
        //                 { name: "no", value: "不符合" },
        //             ],
        //             standard: "3-5",
        //             single: [
        //                 { name: "yes", value: "符合" },
        //                 { name: "no", value: "不符合" },
        //             ],
        //         },
        //     ],
        // },
        // ],
    },

    jump_fubiao(e) {
        app.templateId = this.data.mb_list[e.currentTarget.dataset.index1].id;
        console.log(app.templateId);
        dd.navigateTo({
            url: "/pages/mytest/test_fubiao/test_fubiao",
        });
    },

    //滚动选择器
    bindObjPickerChange(e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            pickerIndex: e.detail.value,
            templateId: this.data.pickerArray[e.detail.value].id,
        });
        this.getTesting();
    },
    bindKeyInput(e) {
        console.log("input", e);
        this.data.form[e.currentTarget.dataset.index1][
            e.currentTarget.dataset.index2
        ].itemResult.res = e.detail.value;
        this.setData({
            form: this.data.form,
        });
    },

    radioChange_single(e) {
        console.log("你选择的单项结论是：", e.detail.value);
        this.data.form[e.target.dataset.index1][
            e.target.dataset.index2
        ].itemResult.single = e.detail.value;
        this.setData({
            form: this.data.form,
        });
    },
    bindKeyInput1(e) {
        this.data.form[e.target.dataset.index1][
            e.target.dataset.index2
        ].itemResult.remark = e.detail.value;
        this.setData({
            form: this.data.form,
        });
    },
    onSubmit: throttle(function(e) {
        let arr = this.data.form.flat();
        // arr.forEach((item) => {
        //     item.itemResult = JSON.stringify(item.itemResult);
        // });

        // console.log(arr);
        // _post1(`/myTest/submitItemResult`, JSON.stringify(arr)).then((res) => {
        //     console.log("提交结果", res);
        //     if (res.data == 0) {
        //         dd.reLaunch({
        //             url: "/pages/mytest/test_list/test_list",
        //         });
        //     } else {
        //         dd.navigateTo({
        //             url: "/pages/mytest/test_fubiao/test_fubiao",
        //         });
        //     }
        // });
        console.log("提交全部", arr);
        let num = 0;
        arr.forEach((item) => {
            if (item.whetherComplete == 1) {
                num++;
            }
        });
        if (arr.length == num) {
            _post(`/myTest/result_submit`, { itemId: app.testing_id }).then((res) => {
                console.log("全部提交", res);
                dd.navigateTo({
                    url: "/pages/mytest/test_list/test_list",
                });
            });
        } else {
            dd.alert({
                content: "请完成全部检测后再提交",
            });
        }
    }, 2000),

    getMb() {
        let params = {
            itemId: app.testing_id,
        };
        _get(`/myTest/get_item`, params).then((res) => {
            this.data.pickerArray = res.data;
            this.data.pickerArray.unshift({
                id: 0,
                templatename: "全部",
            });
            this.setData({
                pickerArray: this.data.pickerArray,
            });
            console.log("pickerArray", this.data.pickerArray);
        });
    },

    getTesting() {
        let params = {
            itemId: app.testing_id,
            templateId: this.data.templateId,
        };
        return _get(`/myTest/selectTemp`, params).then((res) => {
            console.log("检测项内容", res);
            this.data.form = [];
            // this.data.test2_list = [];
            this.data.templateIdArray = [];
            //小程序改变数组方法，先push再setData
            for (let i = 0; i < res.data.data.length; i++) {
                // this.data.test2_list.push([]);
                this.data.form.push([]);
                this.setData({
                    // test2_list: this.data.test2_list,
                    form: this.data.form,
                });
            }
            //有问题
            for (let i = 0; i < res.data.data.length; i++) {
                this.data.templateIdArray.push(res.data.data[i].id);
                for (
                    let j = 0; j < res.data.data[i].myTestItemResultDTOList.length; j++
                ) {
                    if (res.data.data[i].myTestItemResultDTOList[j].result === null) {
                        this.data.form[i].push({
                            test2: res.data.data[i].myTestItemResultDTOList[j].testproject,
                            skillask: res.data.data[i].myTestItemResultDTOList[j].skillask,
                            whetherComplete: res.data.data[i].myTestItemResultDTOList[j].whetherComplete,
                            standard: res.data.data[i].myTestItemResultDTOList[j].referenceResult,
                            single: [
                                { name: "yes", value: "符合" },
                                { name: "no", value: "不符合" },
                                { name: "/", value: "/" },
                            ],
                            itemResult: {
                                res: "",
                                single: "",
                                remark: "",
                            },
                            materials: [],
                            templateItemTestId: res.data.data[i].myTestItemResultDTOList[j].templateItemTestId,
                            userId: app.userId,
                        });
                    } else {
                        this.data.form[i].push({
                            test2: res.data.data[i].myTestItemResultDTOList[j].testproject,
                            skillask: res.data.data[i].myTestItemResultDTOList[j].skillask,
                            whetherComplete: res.data.data[i].myTestItemResultDTOList[j].whetherComplete,
                            standard: res.data.data[i].myTestItemResultDTOList[j].referenceResult,
                            single: [
                                { name: "yes", value: "符合" },
                                { name: "no", value: "不符合" },
                                { name: "/", value: "/" },
                            ],
                            itemResult: JSON.parse(
                                res.data.data[i].myTestItemResultDTOList[j].result
                            ),
                            materials: [],
                            templateItemTestId: res.data.data[i].myTestItemResultDTOList[j].templateItemTestId,
                            userId: app.userId,
                        });
                    }
                }

                // this.data.form.push({
                //     itemResult: {
                //         res: "",
                //         title2: "",
                //         single: "",
                //         remark: "",
                //     },
                //     materials: [],
                //     templateItemTestId: res.data.data[i].templateItemTestId,
                //     userId: app.userId,
                // });
            }
            this.setData({
                form: this.data.form,
                mb_list: res.data.data,
                templateIdArray: this.data.templateIdArray,
                test1: res.data.title,
            });

            // res.data.data.forEach((item1, index1) => {
            //     item1.myTestItemResultDTOList.map((item2, index2) => {
            //         this.setData({
            //             ["test2_list[" + index1 + "]" + "[" + index2 + "]"]: {
            //                 test2: item2.testproject,
            //                 skillask: item2.skillask,
            //                 whetherComplete: item2.whetherComplete,
            //                 standard: item2.referenceResult,
            //                 data: "",

            //                 single: [
            //                     { name: "yes", value: "符合" },
            //                     { name: "no", value: "不符合" },
            //                     { name: "/", value: "/" },
            //                 ],
            //             },
            //         });
            //     });
            // });
        });
    },

    upload_img(e) {
        // console.log('上传图片事件对象', e);
        let index1 = e.currentTarget.dataset.index1;
        let index2 = e.currentTarget.dataset.index2;
        console.log("index1,2", index1, index2);
        let filePath = [];
        dd.chooseImage({
            count: 5,
            success: (res) => {
                filePath = res.filePaths;
                console.log("图片地址", filePath);
                // Promise.all(filePath.forEach(async(item) => {
                //     return await loadimg(`/api/sys/file/importPic`, "image", "file", item).then(
                //         (res) => {
                //             console.log("上传成功", res);
                //         }
                //     );
                // }))
                // loadimg(`/api/sys/file/importPic`, "image", "file", filePath[0]).then(
                //     (res) => {
                //         console.log("上传成功", res);
                //     }
                // );

                //forEach内部不能用异步函数，所以改用for of和立即执行函数
                let that = this;
                (async function filepath() {
                    for (let item of filePath) {
                        await loadimg(
                            `/api/sys/file/importPic`,
                            "image",
                            "file",
                            item
                        ).then((res) => {
                            console.log("上传成功", res);
                            that.data.form[index1][index2].materials.push(res.data);
                            that.setData({
                                form: that.data.form,
                            });
                        });
                    }
                    dd.alert({
                        content: "上传成功",
                    });
                    //   console.log(that.data.form);
                })();
                // filePath.forEach((item) => {
                //     loadimg(`/api/sys/file/importPic`, "image", "file", item).then(
                //         (res) => {
                //             console.log("上传成功", res);
                //             this.data.form[id].materials.push(res.data)
                //             this.setData({
                //                 [`form[` + id + `].materials`]: this.data.form[id].materials
                //             })
                //         }
                //     );
                // })
                // console.log(this.data.form);

                // dd.uploadFile({
                //     url: "http://192.168.1.104:8082/api/sys/file/manyImportPic",
                //     fileType: "image",
                //     fileName: "file",
                //     filePath: filePath[0],
                //     success: (res) => {
                //         dd.alert({
                //             content: "上传成功",
                //         });
                //     },
                // });
                // dd.alert({
                //     title: '选中的图片',
                //     content: JSON.stringify(res.filePaths)
                // })
            },
        });
    },

    upload_video(e) {
        // console.log('上传图片事件对象', e);
        let index1 = e.currentTarget.dataset.index1;
        let index2 = e.currentTarget.dataset.index2;
        console.log("index1,2", index1, index2);
        let filePath = [];
        dd.chooseVideo({
            sourceType: ["album", "camera"],
            maxDuration: 60,
            success: (res) => {
                filePath = res.filePath;
                console.log("视频地址", filePath);
                let that = this;
                (async function filepath() {
                    await loadimg(
                        `/api/sys/file/importPic`,
                        "video",
                        "file",
                        filePath
                    ).then((res) => {
                        console.log("上传成功", res);
                        that.data.form[index1][index2].materials.push(res.data);
                        that.setData({
                            form: that.data.form,
                        });
                    });

                    dd.alert({
                        content: "上传成功",
                    });
                    console.log(that.data.form);
                })();
            },
            fail: (err) => {
                console.log(err);
                throw new Error(err);
            },
        });
    },
    // startRecord() {
    //     let rm = dd.getRecorderManager()
    //     rm.onstart = () => {
    //         dd.alert({ content: 'record onStart' })
    //     }
    //     rm.onstop = (res) => {
    //         dd.alert({ content: 'tempFilePath: ' + res.tempFilePath })
    //     }
    //     rm.onerror = (err) => {
    //         dd.alert({ content: 'onerror' })
    //     }
    //     rm.start({ duration: 5 })
    // },
    // stopRecord() {
    //     let rm = dd.getRecorderManager();
    //     rm.stop();
    // },
    // upload_recorder() {
    //     if (dd.canIUse('getRecorderManager')) { // 端上支持
    //         this.startRecord()
    //     } else { // 端上不支持
    //         dd.alert({ content: '请升级钉钉版本至4.5.18以支持录音功能' })
    //     }

    // },
    async save(e) {
        let params = [];
        params.push(
            JSON.parse(
                JSON.stringify(
                    this.data.form[e.target.dataset.index1][e.target.dataset.index2]
                )
            )
        );
        params.forEach((item) => {
            item.itemResult = JSON.stringify(item.itemResult);
        });
        console.log(params);
        await _post1(`/myTest/submitItemResult`, JSON.stringify(params)).then((res) => {
            console.log("保存", res);
            if (res.errorMessage === "操作成功") {
                dd.alert({
                    content: "保存成功",
                });
            }
        });
        await this.getTesting()
    },
    onLoad() {
        dd.setNavigationBar({
            title: "检测中",
            backgroundColor: "#142e4f",
            success() {},
            fail() {},
        });
        this.getTesting();
        this.getMb();
    },
    onShow() {},
});